﻿using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using System.Reflection;

namespace Common.Standard
{
    public class XmlHelper
    {
        /// <summary>
        /// xml反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="src">json字符串</param>
        /// <returns></returns>
        public static T Deserialize<T>(string str) where T : class
        {
            if (string.IsNullOrEmpty(str))
            {
                throw new Exception("传入参数为空");
            }

            T t = null;
            try
            {
                var list = (typeof(T)).ToString().Split('.');
                var typeName = list[list.Length - 1];
                str = str.Replace("<xml>", string.Format("<{0}>", typeName));
                str = str.Replace("<root>", string.Format("<{0}>", typeName));
                str = str.Replace("</root>", string.Format("</{0}>", typeName));
                str = str.Replace("</xml>", string.Format("</{0}>", typeName));
                using (StringReader sr = new StringReader(str))
                {
                    XmlSerializer xmldes = new XmlSerializer(typeof(T));
                    t = xmldes.Deserialize(sr) as T;
                }
            }
            catch (Exception e)
            {
                throw new Exception($"XML反序列化失败:{e.Message}");
            }
            return t;
        }

        /// <summary>
        /// xml序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string Serialize<T>(T t) where T : class
        {
            if (t == null)
            {
                throw new Exception("空模型");
            }

            using (MemoryStream Stream = new MemoryStream())
            {
                XmlSerializer xml = new XmlSerializer(typeof(T));
                try
                {
                    //序列化对象
                    xml.Serialize(Stream, t);
                }
                catch (Exception e)
                {
                    throw new Exception($"XML序列化失败:{e.Message}");
                }
                Stream.Position = 0;
                StreamReader sr = new StreamReader(Stream);
                string str = sr.ReadToEnd();
                var list = (typeof(T)).ToString().Split('.');
                var typeName = list[list.Length - 1];
                str = str.Replace($"<{typeName} xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">", "<xml>");
                str = str.Replace($"<{typeName} xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">", "<xml>");
                str = str.Replace($"</{typeName}>", "</xml>");
                str = str.Replace("<?xml version=\"1.0\"?>", "");
                return str;
            }
        }
    }
}
